package eai.tp2.core;

import eai.tp2.core.datamodel.Announcement;
import eai.tp2.core.datamodel.CameraSummary;
import eai.tp2.core.datamodel.Resolution;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Element;

/**
 * This class process the brand summarize for each camera list. 
 * 
 */
public class SummaryEngine {

    public List<CameraSummary> process(Map<String, List<Element>> cameras) {
        CameraSummary summary = null;
        List<CameraSummary> list = new ArrayList<CameraSummary>();
        List<String> manufacturerModels;

        for (String brand : cameras.keySet()) {
            List<Element> camerasOfBrand = cameras.get(brand);
            manufacturerModels = new ArrayList<String>();

            initResolutions(camerasOfBrand.get(0));

            for (Element camera : camerasOfBrand) {
                manufacturerModels.add(camera.getChild("name").getValue());
                saveLesserDate(camera);
                saveGreaterDate(camera);
                saveLowerRes(camera);
                saveBiggerRes(camera);
                numCameras++;
            }

            summary = new CameraSummary(brand, numCameras, new Announcement(mostRecentModel, mostRecentDate),
                    new Announcement(oldestModel, oldestDate),
                    new Resolution(maxResModel, stringMaxRes), new Resolution(minResModel, stringMinRes),
                    manufacturerModels);

            list.add(summary);

        }

//        System.out.println("Oldest Date: " + oldestDate.toString());
//        System.out.println("Oldest Model: " + oldestModel);
//        System.out.println("Most Recent Date: " + mostRecentDate.toString());
//        System.out.println("Most Recent Model: " + mostRecentModel);
        return list;
    }

    private void saveLesserDate(Element camera) {
        Format formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {

            date = (Date) formatter.parseObject(camera.getChild("date").getValue());
            if (date.compareTo(oldestDate) <= 0) {
                oldestDate = date;
                oldestModel = camera.getChild("name").getValue();
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void saveGreaterDate(Element camera) {
        Format formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;

        try {
            date = (Date) formatter.parseObject(camera.getChild("date").getValue());
            if (date.compareTo(mostRecentDate) >= 0) {
                mostRecentDate = date;
                mostRecentModel = camera.getChild("name").getValue();
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void saveLowerRes(Element camera) {

        String resolution = camera.getChild("min_res").getValue().trim();
        String[] nums = resolution.split("\\s*x\\s*");
        try {

            //So verifica se o padrao estiver correcto
            if (nums.length == 2) {
                if (minRes > (Integer.parseInt(nums[0]) * Integer.parseInt(nums[1]))) {
                    minRes = Integer.parseInt(nums[0]) * Integer.parseInt(nums[1]);
                    minResModel = camera.getChild("name").getValue();
                    stringMinRes = resolution;
                }

            }

        } catch (NumberFormatException nfe) {
            //nfe.printStackTrace();
        }


    }

    private void saveBiggerRes(Element camera) {

        String resolution = camera.getChild("max_res").getValue().trim();
        String[] nums = resolution.split("\\s*x\\s*");
        try {

            //So verifica se o padrao estiver correcto
            if (nums.length == 2) {
                if (maxRes < (Integer.parseInt(nums[0]) * Integer.parseInt(nums[1]))) {
                    maxRes = Integer.parseInt(nums[0]) * Integer.parseInt(nums[1]);
                    maxResModel = camera.getChild("name").getValue();
                    stringMaxRes = resolution;
                }

            }

        } catch (Exception e) {

            e.printStackTrace();
        }


    }

    /**
     * Method to help in the comparations. It inits the first values
     * @param el
     */
    private void initResolutions(Element el) {
        try {
            Format formatter = new SimpleDateFormat("yyyy-MM-dd");
            mostRecentDate = new Date();
            mostRecentDate = (Date) formatter.parseObject("1900-01-01");
            oldestDate = new Date();
            oldestModel = "";
            mostRecentModel = "";
            stringMaxRes = "";
            maxResModel = "";
            stringMinRes = "";
            minResModel = "";
            numCameras = 0;
            maxRes = 0;
            minRes = Integer.MAX_VALUE;
        } catch (ParseException ex) {
            Logger.getLogger(SummaryEngine.class.getName()).log(Level.INFO, "Error initializing the variables.", ex);
        }

    }

   
    private Date oldestDate = new Date();
    private String oldestModel = "";
    private Date mostRecentDate = new Date();
    private String mostRecentModel = "";
    private String stringMaxRes;
    private int maxRes;
    private String maxResModel = "";
    private String stringMinRes;
    private int minRes;
    private String minResModel = "";
    private int numCameras;
    public static final String MOST_RECENT = "most_recent";
    public static final String OLDEST = "oldest";
    public static final String MAX_RES = "max_res";
    public static final String MIN_RES = "min_res";
    public static final String MODEL_LIST = "model_list";
}
